import os
from flask import request, jsonify
from src.api.controllers.merge_controller import MergeController
from src.utils.logger import log_info
from src.config import OUTPUT_DIR

def register_merge_routes(bp):
    controller = MergeController()
    
    @bp.route('/merge/process', methods=['POST'])
    def process_merge():
        data = request.json
        prompt_data = data.get('prompt_data', [])
        # output_folder = data.get('output_folder', '')
        output_folder = OUTPUT_DIR
        audio_ids = data.get('audio_ids', [])  # 添加音频路径参数
        transition_effect = data.get('transition_effect', 'fade')        
        settings = {
            'generate_all': data.get('generate_all', False),
            'remove_voice': data.get('remove_voice', False),
            'random_limit': int(data.get('random_limit', 3))
        }
        
        # 日期范围
        date_range = {
            'start_date': data.get('start_date'),
            'end_date': data.get('end_date')
        }
        
        log_info(f"接收到混搭请求: 提示数量={len(prompt_data)}, 输出目录={output_folder}, 音频路径={audio_ids}")
        result = controller.process_merge(
            prompt_data=prompt_data, 
            output_folder=output_folder,
            settings=settings,
            date_range=date_range, 
            audio_ids=audio_ids,
            transition_effect=transition_effect
                                          )
        return jsonify(result)
  
    @bp.route('/merge/status', methods=['GET'])
    def get_merge_status():
        result = controller.get_status()
        return jsonify(result)
        
    @bp.route('/merge/stop', methods=['POST'])
    def stop_merge():
        log_info("接收到停止混搭请求")
        result = controller.stop_processing()
        return jsonify(result)
    
    @bp.route('/merge/video-audio', methods=['POST'])
    def merge_video_audio():
        data = request.json
        controller = MergeController()
        
        video_path = data.get('video_path')
        audio_path = data.get('audio_path')
        output_path = data.get('output_path')
        settings = data.get('settings', {})
        
        result = controller.merge_video_with_audio(video_path, audio_path, output_path, settings)
        return jsonify(result)
    
    @bp.route('/merge/audio', methods=['POST'])
    def upload_audio_abandon():
        """处理音频文件上传请求"""
        # 检查请求中是否有文件
        if 'audio_file' not in request.files:
            return jsonify({"success": False, "message": "未提供音频文件"}), 400
        
        audio_file = request.files['audio_file']
        subtitle_file = request.files['subtitle_file'] if 'subtitle_file' in request.files else None
        
        group_id = request.form.get('group_id')
        # if not group_id:
            # return jsonify({"success": False, "message": "未提供组ID"})

        # 获取目标目录（如果提供）
        target_directory = request.form.get('directory', None)
        
        meta_data = request.form.get('meta_data', None)
        order = request.form.get('order', 0)
        
        log_info(f"接收到文件上传请求: 文件名={audio_file.filename}, 组ID={group_id}, 目录={target_directory}, 顺序={order}")        
        if subtitle_file:
            log_info(f"接收到字幕文件: {subtitle_file.filename}")
        # 处理文件上传
        result = controller.upload_audio(audio_file, group_id, order, subtitle_file, target_directory, meta_data)
        return jsonify(result)
    
    @bp.route('/merge/clear_logs', methods=['POST'])
    def clear_logs():
        """清除日志文件"""
        log_info("接收到清除日志请求")
        result = controller.clear_logs()
        return jsonify(result)
    
    
    @bp.route('/merge/process_by_ids', methods=['POST'])
    def process_merge_by_ids():
        data = request.json
        prompt_data = data.get('prompt_data', [])
        output_folder = OUTPUT_DIR
        video_ids = data.get('video_ids', [])  # New parameter for specific video IDs
        audio_ids = data.get('audio_ids', [])
        transition_effect = data.get('transition_effect', 'fade')        
        
        settings = {
            'generate_all': data.get('generate_all', False),
            'remove_voice': data.get('remove_voice', False),
            'random_limit': int(data.get('random_limit', 3))
        }
        
        # 日期范围 (保持一致性)
        date_range = {
            'start_date': data.get('start_date'),
            'end_date': data.get('end_date')
        }
        
        log_info(f"接收到按ID混搭请求: 提示数量={len(prompt_data)}, 视频ID数量={len(video_ids)}, "
                f"输出目录={output_folder}, 生成所有组合={settings['generate_all']}")
        
        result = controller.process_merge_by_ids(
            prompt_data=prompt_data, 
            output_folder=output_folder,
            settings=settings,
            date_range=date_range, 
            audio_ids=audio_ids,
            transition_effect=transition_effect,
            video_ids=video_ids
        )
        
        return jsonify(result)
    
    @bp.route('/merge/add_intro_outro', methods=['POST'])
    def add_intro_outro():
        """为视频添加片头片尾"""
        data = request.get_json()
        
        video_path = data.get('video_path')
        video_id = data.get('video_id')
        output_folder = data.get('output_folder')
        opening_file_id = data.get('opening_file_id')
        ending_file_id = data.get('ending_file_id')
        transition_effect = data.get('transition_effect', 'fade')
        
        merger = MergeController()
        
        if video_path:
            if not os.path.exists(video_path):
                return jsonify({"success": False, "message": "视频文件不存在"}), 400
                
            result = merger.add_opening_ending_to_video(
                video_path=video_path,
                output_folder=output_folder,
                opening_file_id=opening_file_id,
                ending_file_id=ending_file_id,
                transition_effect=transition_effect
            )
        elif video_id:
            result = merger.add_opening_ending_to_video_by_id(
                video_id=video_id,
                output_folder=output_folder,
                opening_file_id=opening_file_id,
                ending_file_id=ending_file_id,
                transition_effect=transition_effect
            )
        else:
            return jsonify({"success": False, "message": "必须提供video_path或video_id参数"}), 400
            
        return jsonify(result)

    @bp.route('/merge/process_folder_intro_outro', methods=['POST'])
    def process_folder_intro_outro():
        """批量为文件夹中的视频添加片头片尾"""
        data = request.get_json()
        
        if not data or 'folder_path' not in data:
            return jsonify({"success": False, "message": "必须提供folder_path参数"}), 400
            
        folder_path = data.get('folder_path')
        output_folder = data.get('output_folder')
        opening_file_id = data.get('opening_file_id')
        ending_file_id = data.get('ending_file_id')
        transition_effect = data.get('transition_effect', 'fade')
        
        merger = MergeController()
        result = merger.process_folder_add_intro_outro(
            folder_path=folder_path,
            output_folder=output_folder,
            opening_file_id=opening_file_id,
            ending_file_id=ending_file_id,
            transition_effect=transition_effect
        )
        
        return jsonify(result)